#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from django import forms
from django.forms import widgets
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import ugettext as _
from blogmaker.blog.models import Tag, Entry
from PIL import Image
import StringIO

class EntryForm(forms.Form):
    headline = forms.CharField(max_length=255, required=True, label=_('Titol'), widget=widgets.TextInput(attrs={"size": 75}))
    slug = forms.CharField(max_length=120, required=True, widget=widgets.TextInput(attrs={"size": 75}))
    pub_date = forms.DateTimeField(required=True, label=_('Data i hora'),
                help_text=_("Format: 'YYYY-MM-DD HH:MM:SS'"))
    #summary = forms.CharField(maxlength=255, null=True, blank=True, help_text="Leave this field blank")
    image = forms.ImageField(widget=widgets.FileInput, required=False, label=_('Imatge'), 
            help_text=_("L'amplada ha de ser inferior a 468px"))
    copyright = forms.CharField(max_length=255, required=False, help_text=_("Atribucio de la imatge"), widget=widgets.TextInput(attrs={"size": 75}))
    body = forms.Field(widget=widgets.Textarea(attrs={"rows": 25, "cols": 73}))
    active = forms.BooleanField(help_text=_("Ha de ser l'article visible?"))
    
    _userChoices = [ (user.id, user.username) for user in User.objects.all() ]
    _tagChoices = [ (tag.id, tag.tag) for tag in Tag.objects.all() ]
    _entryChoices = [ (entry.id, entry.headline[:95]) for entry in Entry.objects.all() ]
    
    user = forms.ChoiceField(label=_("Usuari"), choices=_userChoices, required=True)
    tags = forms.MultipleChoiceField(choices=_tagChoices, required=False)
    related_entries = forms.MultipleChoiceField(label=_("Articles relacionats"), choices=_entryChoices, required=False)
    externalId = forms.IntegerField(label=_("Id externa"), required=False)
    
    def clean_image(self):

        if self.cleaned_data.get('image'):
            image_data = self.cleaned_data['image']
            try:
                img = Image.open(StringIO.StringIO(image_data.content))
                content_type = img.format.upper()
            except:            
                raise forms.ValidationError(_('Puja una imatge vàlida. La imatge no era valida o és defectuosa.'))
                
            if not (content_type in ['JPEG', 'GIF', 'PNG', 'JPG', 'X-PNG', 'PJPEG']):
                raise forms.ValidationError(_('Els formats admesos son JPG, PNG y GIF'))
                    
            size = len(image_data.content)
            if size > 1000000:
                raise forms.ValidationError(_('La imatge es massa gran'))
                
            width, height = img.size
            if width > 468:
                raise forms.ValidationError(_("L'amplada maxima és 468px"))
        return self.cleaned_data['image']

 
